package com.elight.utils;

import java.util.ArrayList;
import java.util.List;

import com.elight.entity.TreeSelect;

public class TreeSelectHelper {
	public static String ToTreeSelectJson(List<TreeSelect> data)
    {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        sb.append(ToTreeSelectJson(data, null, ""));
        sb.append("]");
        return sb.toString();
    }
    private static String ToTreeSelectJson(List<TreeSelect> data, String parentId, String blank)
    {
        StringBuilder sb = new StringBuilder();
        List<TreeSelect>  childList = findChild(data,parentId);//data.FindAll(t => t.parentId == parentId);
        String tabline = "";
        if(parentId != null && !parentId.equals("0")){
            tabline = "　　";
        }
        if (childList.size() > 0)
        {
            tabline = tabline + blank;
        }
        for(TreeSelect entity : childList)
        {
            entity.text = tabline + entity.text;
            String strJson =GsonUtils.objToJSON(entity);
            sb.append(strJson);
            sb.append(ToTreeSelectJson(data, entity.id, tabline));
        }
        return sb.toString().replace("}{", "},{");
    }
    
	private static List<TreeSelect> findChild(List<TreeSelect> data, String parentId) {
		List<TreeSelect> retList=new ArrayList<TreeSelect>();
		for(TreeSelect item : data){
		    if(checked(parentId,item.getParentId())){
                retList.add(item);
            }
		}
		return retList;
	}

	private static boolean checked(String parentId,String checkParentId){
	    if(parentId == null){
            if(checkParentId==null)
                return true;
            if(checkParentId.equals(""))
                return true;
            if(checkParentId.equals("0")){
                return true;
            }
            return false;
        }else
        {
            if(checkParentId==null)
                return false;
            return parentId.equals(checkParentId);
        }


    }
}
